<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="index.css">
  <script src="js/jquery-1.12.4.min.js"></script>
  <script src="js/template-native.js"></script>
  <!-- 创建模板 -->
  <script id="tem" type="text/html">
    <% for (let i = 0; i < comments.length; i++) { %>
        <li idx = "<%= comments[i].id %>">
          <p class="floor">
            <%= comments[i].id %>楼<a href="javascript:;" class="delete">删除</a>
          </p>
          <p class="author">层主：<span class="name">
              <%= comments[i].username %>
            </span></p>
          <p class="content">
            <%= comments[i].comment %>
          </p>
        </li>
    <% } %>
  </script>
</head>
<body>
  <div class="main">
    <div class="post">
      <h2>影视推荐</h2>
      <p class="author">楼主：喵里个喵</p>
      <p class="txt">各位小伙伴有什么好看的剧推荐嘛！</p>
    </div>
    <div class="reply">
      <h4>发表回复</h4>
      <p>用户名：<input type="text" class="user"></p>
      <textarea class="editor"></textarea>
      <input type="button" value="发表" class="btn">
    </div>
    <div class="cmts">
      <ul class="list">
        <!-- <li>
          <p class="floor">
            1楼<a href="javascript:;" class="delete">删除</a>
          </p>
          <p class="author">层主：<span class="name">
              hhh
            </span></p>
          <p class="content">
            同意
          </p>
        </li> -->
      </ul>
    </div>
  </div>
  <script>
    let $list = $(".list");
    let $btn = $(".btn");
    let $user = $(".user");
    let $editor = $(".editor");
    
    // 获取后台数据
    $.ajax({
      url:"http://localhost:3000/db",
      type: "GET",
      success: function(data) {
        $list.html(template("tem",data));
        deleteComment();
      }
    });


    // 点击发表按钮，增加一条数据
    $btn.click(function(){
      let username = $user.val();
      let comment = $editor.val();
      $.ajax({
        url: "http://localhost:3000/comments",
        type: "POST",
        dataType: "json",
        data: {username:username,comment:comment},
        success:function (data){
          $list.append(template("tem",{"comments":[data]}));
          deleteComment();
        }
      });
      $user.val('');
      $editor.val('');
      
    })

    // 点击删除按钮，删除相应的li标签
    function deleteComment() {
      let $delete = $(".delete");
      $delete.click(function(){
        let $li = $(this).parents("li");
        let index = $li.attr("idx");
        $.ajax({
          url: "http://localhost:3000/comments/" + index,
          type: "DELETE"
        });
        $li.remove();
      })
    }
  </script>
</body>
</html>